<script setup lang="ts">
import { ref } from 'vue'
import { useUserStore } from '@/stores/user'

interface CheckboxChangeEvent {
  detail: {
    value: boolean
  }
}

// 定义响应数据类型
interface LoginResponse {
  email: string;
  gender: string;
  wechat_openid: string;
  user_id: string;
  phone: string;
  nickname: string;
  access: string;
  refresh: string;
  avatar: string;
  message?: string;
  created_at:string;
  is_wechat_bound:boolean;
  is_lock:boolean
}

const userStore = useUserStore()
const errorMsg = ref('')
const code = ref('')
const isAgreed = ref(false)

// 处理微信一键登录
const handleWechatLogin = async (e: any) => {
  if (!isAgreed.value) {
    uni.showToast({
      title: '请先同意用户协议和隐私政策',
      icon: 'none'
    })
    return
  }
  console.log('[关键节点] 微信登录回调:', e)

  if (e.detail.errMsg !== 'getPhoneNumber:ok') {
    const msg = e.detail.errMsg === 'getPhoneNumber:fail user deny'
      ? '用户已取消'
      : '获取手机号失败'

    uni.showToast({
      title: msg,
      icon: 'none'
    })
    errorMsg.value = msg
    return
  }

  try {
    // 1. 获取微信登录code
    const loginRes = await uni.login({
      provider: 'weixin'
    })

    if (!loginRes.code) {
      throw new Error('获取微信登录code失败')
    }

    code.value = loginRes.code
    console.log('[关键节点] 获取到微信登录code:', code.value)

    // 2. 获取系统信息
    const systemInfo = uni.getSystemInfoSync()

    // 3. 发送登录请求
    const { encryptedData, iv } = e.detail
    const res = await uni.request({
      url: 'https://52d47b77.r34.cpolar.top/api/account/wechat/login/',
      method: 'POST',
      data: {
        code: code.value,
        encryptedData,
        iv,
          deviceId: systemInfo.deviceId || ''
      },
      header: {
        'content-type': 'application/json'
      }
    })

    const { data, statusCode } = res
    const responseData = data as LoginResponse

    console.log('[关键节点] 登录响应详情:',   res)

    // 4. 处理响应
    if (statusCode === 200 && responseData) {
      if (responseData.access) {
        const newUserInfo = {
          id: responseData.user_id,
          phone: responseData.phone,
          nickname: responseData.nickname || '用户' + responseData.user_id?.slice(-4),
          access_token: responseData.access,
          refresh_token: responseData.refresh,
          is_wechat_bound: true,
          avatarUrl: responseData.avatar,
          openid: responseData.wechat_openid,
          email:responseData.email,
          gender:responseData.gender,
          is_lock:responseData.is_lock
        }
        console.log('[关键节点] 用户信息:', newUserInfo)
        userStore.setUserInfo(newUserInfo)
        uni.showToast({
          title: '登录成功',
          icon: 'success'
        })
        setTimeout(() => {
          uni.switchTab({ url: '/pages/home/home' })
        }, 1500)
      } else {
        console.error('[关键节点] 响应数据缺少access字段:', responseData)
        throw new Error(responseData.message || '登录失败')
      }
    } else {
      console.error('[关键节点] 响应异常:', { statusCode, data: responseData })
      throw new Error('服务器响应异常')
    }
  } catch (error: any) {
    console.error('[关键节点] 登录失败:', error)
    errorMsg.value = error.message || '登录失败，请重试'
    uni.showToast({
      title: error.message || '登录失败，请重试',
      icon: 'none'
    })
  }
}
// 查看用户协议
const showAgreement=()=>{
  uni.navigateTo({
    url: '/pages/agreement/userAgreement'
  })
}
// 查看隐私协议
const showprivacy=()=>{
  uni.navigateTo({
    url: '/pages/agreement/privacyPolicy'
  })
}

// 处理返回上一页
const handleBack = () => {
  uni.navigateBack()
}
</script>



<template>
  <view class="login-container">
    <!-- 返回按钮 -->
    <view class="back-button" @click="handleBack">
      <image class="back-icon" src="/static/back.png" mode="aspectFit"></image>
    </view>

    <!-- 背景图 -->
    <!-- <image
      class="background-image"
      src="/static/images/login-bg.jpg"
      mode="aspectFill"
    /> -->

    <!-- 内容容器 -->
    <view class="content-wrapper">
      <!-- 顶部LOGO -->
      <!-- <image
        class="logo"
        src="/static/images/logo.png"
        mode="aspectFit"
      /> -->

      <!-- 提示文字 -->
      <view class="login-tip">
        <text class="welcome">欢迎使用</text>
        <text class="app-name">AI企业神经触点</text>
      </view>

      <!-- 错误提示 -->
      <view v-if="errorMsg" class="error-message">
        {{ errorMsg }}
      </view>

      <!-- 一键登录按钮 -->
      <button
        class="wechat-login-btn"
        open-type="getPhoneNumber"
        @getphonenumber="handleWechatLogin"
      >
        <!-- <image
          class="wechat-icon"
          src="/static/images/wechat-icon.png"
          mode="aspectFit"
        /> -->
        <text class="button-text">微信一键登录</text>
      </button>

      <!-- 隐私政策 -->
      <view class="privacy-policy">
        <checkbox
          :checked="isAgreed"
          @tap="isAgreed = !isAgreed"
          class="agreement-checkbox"
        />
        <text>登录即表示同意</text>
        <text class="link" @click="showAgreement">《用户协议》</text>
        <text>和</text>
        <text class="link" @click="showprivacy">《隐私政策》</text>
      </view>
    </view>
  </view>
</template>

<style>
.login-container {
  position: relative;
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  filter: blur(10px) brightness(0.7);
}

.content-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 60rpx 40rpx;
  border-radius: 24rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
  width: 80%;
  max-width: 600rpx;
}

.logo {
  width: 180rpx;
  height: 180rpx;
  margin-bottom: 40rpx;
}

.login-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 60rpx;
}

.welcome {
  font-size: 32rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.app-name {
  font-size: 40rpx;
  color: #1b1b2f;
  font-weight: bold;
}

.error-message {
  color: #ff4d4f;
  font-size: 24rpx;
  margin-bottom: 20rpx;
  text-align: center;
}

.wechat-login-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 88rpx;
  background-color: #07c160;
  border-radius: 44rpx;
  border: none;
  padding: 0;
  margin-bottom: 30rpx;
}

.wechat-icon {
  width: 44rpx;
  height: 44rpx;
  margin-right: 16rpx;
}

.button-text {
  font-size: 32rpx;
  color: #fff;
  font-weight: 500;
}

.privacy-policy {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  justify-content: center;
  font-size: 24rpx;
  color: #999;
  margin-top: 20rpx;
}

.agreement-checkbox {
  margin-right: 10rpx;
  transform: scale(0.8);
}

.link {
  color: #4080ff;
  display: inline;
}

.wechat-login-btn:active {
  opacity: 0.9;
}

.back-button {
  position: fixed;
  top: 40rpx;
  left: 40rpx;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 50rpx;
  z-index: 100;
}

.back-icon {
  width: 60rpx;
  height: 60rpx;
}
</style>
